#!/usr/bin/perl
#
# Display info about a Person, with the option to
# edit, and to push lots of buttons to do things with his Place.
#
use LinuxCounter;
use FileTable;
use Fcntl;
use Counter::CGI;
use ErrorForm;
use CounterCGI;
use Validate::Places;
use Validate::Persons;
use Counter;

$] > 5.008 && binmode(STDOUT, ":utf8"); # set web page output to utf-8
$q = new Counter::CGI;
$users = Counter::open(O_RDONLY);
$persons = Counter::openfile("persons");
$places = Counter::openfile("places");

$key = $q->param('user');
if ($key =~ /@/) {
    $userrec = $users->getbyemail($key);
} else {
    $userrec = $users->get($key);
}
if (!$userrec) {
    errorForm(__("No user record for") . " " . $key);
}
$key = $userrec->key();
$rec = $persons->getclean($key);
$rawrec = $persons->get($rec->key) if $rec;
# see if patching is wanted
if ($rawrec && $q->param("patchfield")) {
    $patchfield = $q->param("patchfield");
    $value = $q->param("patchvalue");
    $oldvalue = $rawrec->{$patchfield};
    if (defined($value)) {
	$rawrec->{$patchfield} = $value;
    } else {
	delete $rawrec->{$patchfield};
    }
    $rawrec->store();
}
print <<EoF;
Content-type: text/html; charset="utf-8"

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
EoF
CounterCGI::pagehead(__("Admin information for") . " " . $key);
print "<body bgcolor=\"white\">\n";
CounterCGI::pagetop($q);
if ($patchfield) {
    print "<em>", __("Changed"), " ", $patchfield, __("from"), " " , "\"$oldvalue\"", " ", __("to"), " ", "\"$value\"</em>\n";
}

if (!$rec) {
print "<h1><img src=\"/cgi-bin/certificate.cgi/$key\"",
    "alt=\"", __("Registered Linux User"), " #$key\" align=middle> (", __("no person record"), ")</h1>\n";
    admininfo();
} else {
print "<h1><img src=\"/cgi-bin/certificate.cgi/$key\"",
    "alt=\"", __("Registered Linux User"), " #$key\" align=middle> ", $$rec{name}, "</h1>\n";
print "<p>\n";
    admininfo();
    print "<table border=2>\n<tr>\n<td>\n"; # table around personinfo
    print "<b>", __("Person info"), "<br>(", __("as entered"), ")</b>\n";
    print "</td>\n<td><b>", __("Associated emails"), "</b>\n</td>\n</tr>";
    print "<tr>\n<td>";
    printPersonTable($rawrec);
    print "</td>\n<td>\n";
    print "<table>\n"; # table of emails
    print "<tr>\n<th>", __("Use"), "</th>\n<th>", __("Email"), "</th>\n<th>", __("State"), "</th>\n</tr>\n";
    @emails = $userrec->emails();
    for $mail (sort {$$a{usage} cmp $$b{usage}} @emails) {
        my $my_email = htmlquote($mail->key());
        $my_email =~ s/@/&#x40;/g;
	print "<tr>\n<td>$$mail{usage}</td>\n<td>",
	        $my_email, "</td>\n<td>$$mail{state}</td>\n</tr>\n";
    }
    print "</table>\n</td>\n</tr>\n"; # table of emails
    print "</table>\n"; # table around personinfo
print "<p>\n";
print __("The record ID is"), " ", $key, "<br>\n";
print __("Record last updated"), ": $$rec{recdate}<br>\n";
} # end user record present

print <<EoF;
<form method=post action="/cgi-bin/adm/show-user.cgi">
<input type=hidden name="key" value=$key>
EoF
print "<input type=\"submit\" value=\"", __("Update"), "\">\n";
print <<EoF;
</form>
<form method=post action="/cgi-bin/adm/merge.cgi">
EoF
print __("Merge with key"), " ";
print <<EoF;
<input name="key2" size=10>
<input type=hidden name="key" value=$key>
EoF
print "<input type=\"submit\" value=\"", __("Merge"), "\">\n";
print "</form>\n";

if ($rec) {
   print "<hr>\n<h2>", __("Place info"), "</h2>\n";

#
# Print place info, with lots of interesting buttons and input fields
# to change it if it doesn't look perfect.
#

    ($country, $state, $city, $myplace) = Validate::Places::findplaces($rawrec);
    print __("The place ID for this record is"), " $$myplace{name}<p>\n";
    $placesource = $rec->{placesource};
    if ($$myplace{name} ne $$rec{placeid}) {
	$rawrec->clean();
	print __("This isn't the same as what's in the record; the record has been cleaned. Please push Reload."), "<p>\n";
    } elsif ($placesource eq "clean-email") {
	print __("This guy got his placement in the places tree based on his email address, which probably means some of his basic attributes (like country) were blank or wrong. The code to make sense of this situation isn't here yet - look at the stuff below and then press the \"update\" button above."), "<p>\n";
	print "<table border=2>\n<tr>\n<th>", __("Field"), "</th>\n<th>", __("Entered"), "</th>\n<th>", __("Interpreted"), "</th>\n</tr>\n";
	for $field (qw(country state city)) {
	    print "<tr>\n<td>$field</td>\n<td>", $rawrec->{$field}, "</td>\n<td>",
	    $rec->{$field}, "</td>\n</tr>\n";
	}
	print "</table>\n";
	$myself = $q->self_url();
	print "<a href=\"/cgi-bin/adm/display-person.cgi?user=$key&patchfield=country&patchvalue=$$rec{country}\">";
	print __("Place computed country into record"), "</a>";
    } elsif ($placesource ne "clean-placename" 
	     && $placesource ne "clean-alias") {
	print __("The place ID was determined by"), " $placesource. ", __("Take care."), "<p>\n";
    } else { # placename & alias go here
	if ($placesource eq "clean-alias") {
	    print __("The alias"), " $$rec{placealias} ", __("was used to find this person's place"), "<p>\n";
	}
	if ($country->{type} ne "country") {
	    print __("Country"), " $$rec{country} ", __("isn't listed in the places DB?"), "<br>\n";
	}
	if ($rec->{state} && !$state) {
	    print __("State/province/department"), " $$rec{state} ", __("isn't listed in the places DB?"), "<br>\n";
	}
	if ($rec->{city} && !$city) {
	    print __("City"), " $$rec{city} ", __("isn't listed in the places database"), "<br>\n";
	    print __("You may want to take one of the actions listed below"), "<br>\n";
	    $trythis = substr($$rec{city}, 0, 3);
	    if ($myplace->{type} eq "state") {
		$searchscope = "$$myplace{name}";
		$namecontext = "$$myplace{name}";
	    } else {
		$searchscope = "$$myplace{name}:%";
		$namecontext = "$$myplace{name}:";
	    }
	    $asciified = Validate::Places::namecase($$rec{city});
            my $placekey = $myplace->key();
	    print <<EoF;
<hr>
<form method="POST" action="addform.cgi">
<input type=hidden name="db" value="db/places">
<input type=hidden name="form" value="i18n/wwws/adm/placerec.php">
<!-- Values for the new record -->
<input type=hidden name="within" value="$placekey">
<input type=hidden name="type" value="city">
<input type=hidden name="name" value="$namecontext:$asciified">
<input type=hidden name="longname" value="$$rec{city}">
EoF
print __("Declare"), " $$rec{city} ", __("to be a valid city under"), " $$myplace{name}\n";
print "<input type=\"submit\" value=\"", __("Do it"), "!\">";
print <<EoF;
</form>
<hr>
EoF

            while ($trythis ne "") {
		chop $trythis;
		warn "Trying search for $searchscope:$trythis\n";
		@placeshere = $places->select("(name like '$searchscope:$trythis%'"
					  . " or name like '%:$$rec{city}')"
					  . " and type = 'city' order by name");
		last if @placeshere + 0 >= 3; 
	    }
	    if (@placeshere + 0 > 0) {
		print __("Places that might fit"), ":\n<ul>\n";
		for $place (@placeshere) {
		    print "<li>", $place->{name}, " <i>", $place->{longname}, "</i></li>\n";
		}
		print <<EoF;
</ul>
<form method="POST" action="addform.cgi">
<input type=hidden name="db" value="db/places">
<input type=hidden name="form" value="i18n/wwws/adm/placerec.php">
<!-- Values for the new record -->
<input type=hidden name="type" value="alias">
<input type=hidden name="name" value="$namecontext:$asciified">
<input type=hidden name="longname" value="$$rec{city}">
EoF
print __("Declare"), " $$rec{city} ", __("an alias for"), " <select name=\"within\">";
                for $place (@placeshere) {
		    my $placekey = $place->key();
		    print "<option value=\"$placekey\">$$place{name}\n";
		}
		print "</select>\n";
		print "<input type=\"submit\" value=\"", __("Do it"), "!\">\n</form>\n";
		
	    }
	}
    }
} # if $rec
# 

CounterCGI::pagebottom("yes");
print <<EoF;
<br>
</body>
</html>
EoF

sub admininfo {
# Print admin info from userrec
my $my_email = $$userrec{email};
$my_email =~ s/@/&#x40;/g;

print "<table cellpadding=1>\n";
print "<tr><td>", __("State"), "</td><td>$$userrec{state}</td></tr>\n";
print "<tr><td>", __("Contact email"), "</td><td>$my_email</td></tr>\n";
print "<tr><td>", __("Login time"), "</td><td>$$userrec{logintime}</td></tr>\n";
print "<tr><td>", __("Created"), "</td><td>$$userrec{f_ctime}</td></tr>\n";
print "<tr><td>", __("Modified"), "</td><td>$$userrec{f_mtime}</td></tr>\n";
    if ($$userrec{login}) {
	print "<tr><td>", __("Login name"), "</td><td>$$userrec{login}</td></tr>\n";
    }
    if ($$userrec{comment}) {
	print "<tr><td>", __("Comment"), "</td><td>$$userrec{comment}</td></tr>\n";
    }
    print "</table>\n";
}

